/*
 * @Description:
 * @Version: 1.0
 * @Autor: zhangwei
 * @Date: 2023-08-18 14:14:11
 * @LastEditors: 463997479@qq.com
 * @LastEditTime: 2025-10-06 10:59:42
 */

import {
  addUser,
  deleteDeptUserPre,
  getUserByMobile,
  updateDeptUserPre,
} from '@/services/ant-design-pro/dept';
import {
  addKnowledge,
  applyKnowledge,
  editKnowledge,
  getIntelligentAgent,
  getKnowledgeIndexList,
  getKnowledgeList,
} from '@/services/ant-design-pro/home/index';
import { ActionType } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { useRequest } from 'ahooks';
import { Form, message } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { createContainer } from 'unstated-next';

export default createContainer(() => {
  const { selectedKeys } = useModel('useTree', (model) => {
    return {
      selectedKeys: model.selectedKeys,
    };
  });
  const [editSystemVisible, setEditSystemVisible] = useState(false);
  const [total, setTotal] = useState(0);

  const [applyVisible, setApplyVisible] = useState(false);
  //智能体弹窗
  const [angentVisible, setAngentVisible] = useState(false);
  const [disabled, setDisabled] = useState(false);
  //部门权限弹窗
  const [permisionVisible, setPermisionVisible] = useState(false);

  const [activeKey, setActiveKey] = useState('1');
  //智能体数据
  const [ligentAgentData, setLigentAgentData] = useState<any>([]);

  //知识库弹窗
  const [corpuVisible, setCorpuVisible] = useState(false);
  const [addUserVisible, setAddUserVisible] = useState(false);
  //知识库详情
  const [detail, setDetail] = useState<Record<any, any>>({});
  const [userData, setUserData] = useState<Record<any, any>>({});
  //新增知识库
  const [form] = Form.useForm();
  //智能体
  const [formAgent] = Form.useForm();

  //知识库修改
  const [formCorpus] = Form.useForm();

  //授权知识库
  const [formApply] = Form.useForm();
  //知识库数据
  const [data, setData] = useState<any>([]);
  //首页数据
  const [dataList, setDataList] = useState<any>([]);
  //知识库的类型
  const [type, setType] = useState<any>('');
  const actionRef = useRef<ActionType>();

  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  useEffect(() => {
    formCorpus.setFieldValue('type', type);
  }, [type]);

  /**
   * 获取当前知识库
   */
  const getData = useRequest(
    async (val: any) => {
      const res = await getKnowledgeList({
        ...val,
        deptCode: selectedKeys.length === 0 ? '' : selectedKeys.toString(),
      });
      console.log(res);
      setTotal(res?.total);
      setData(res);
    },
    { manual: true },
  );

  /**
   *获取首页数据
   */
  const getKnowledgeIndex = useRequest(
    async ({}) => {
      const res = await getKnowledgeIndexList({});

      setDataList(res);
    },
    { manual: true },
  );
  /**
   * 获取智能体
   */
  const getLligentAgent = useRequest(
    async () => {
      const res = await getIntelligentAgent({});
      const arr = res?.data?.map((item) => {
        return {
          ...item,
          label: item?.lntelligentName,
          value: item.id,
        };
      });
      setLigentAgentData(arr);
      setAngentVisible(true);
    },

    { manual: true },
  );
  /**
   * 新增知识库
   */
  const addKnowledgeContent = useRequest(
    async (vals: object) => {
      const res: any = await addKnowledge({
        ...vals,
        deptCode: currentUser?.deptCode,
      });

      if (res) {
        message.success('添加成功', 0.6);
        setCorpuVisible(false);
        getData.refresh();
      } else {
        message.error(`添加失败，错误信息：!`, 0.5);
      }
    },
    { manual: true },
  );
  const getUser = useRequest(
    async (vals: object) => {
      const res: any = await getUserByMobile({
        mobile: vals,
      });

      if (res) {
        console.log(res);
        setUserData(res.data);
      } else {
        message.error(`添加失败，错误信息：!`, 0.5);
      }
    },
    { manual: true, debounceWait: 1000 },
  );
  /**
   * 编辑知识库
   */
  const editKnowledgeContent = useRequest(
    async (vals: object) => {
      const res: any = await editKnowledge({
        ...vals,
        deptCode: currentUser?.deptCode,
      });

      if (res) {
        message.success('修改成功', 0.6);
        setCorpuVisible(false);
        setAngentVisible(false);
        getData.refresh();
      } else {
        message.error(`标签信息更新失败，错误信息：!`, 0.5);
      }
    },

    { manual: true },
  );
  const applyKnowledgeData = useRequest(
    async (vals: object) => {
      const res: any = await applyKnowledge({
        ...vals,
      });
      if (res) {
        message.success('申请成功等待审核', 0.6);
        setApplyVisible(false);
        // getData.refresh();
      } else {
        message.error(`申请失败，错误信息：!`, 0.5);
      }
    },
    { manual: true },
  );

  const addUserList = useRequest(
    async (vals: object) => {
      const res: any = await addUser({
        ...vals,
      });
      if (res) {
        message.success('添加成功', 0.6);
        setAddUserVisible(false);
        setUserData({});
        actionRef.current?.reload();
        // getData.refresh();
      } else {
        message.error(`添加失败!`, 0.5);
      }
    },
    { manual: true },
  );

  const updateDept = useRequest(
    async (vals: object) => {
      const res: any = await updateDeptUserPre({
        ...vals,
      });
      if (res) {
        message.success('更新成功', 0.6);
        setPermisionVisible(false);
        actionRef.current?.reload();
        // getData.refresh();
      } else {
        message.error(`更新失败!`, 0.5);
      }
    },

    { manual: true },
  );
  const deleteDept = useRequest(
    async (vals: number) => {
      const res: any = await deleteDeptUserPre(vals);
      if (res) {
        message.success('删除成功', 0.6);
        actionRef.current?.reload();
        // getData.refresh();
      } else {
        message.error(`删除失败!`, 0.5);
      }
    },

    { manual: true },
  );

  return {
    getData,
    form,
    editSystemVisible,
    setEditSystemVisible,
    corpuVisible,
    setCorpuVisible,
    formCorpus,
    addKnowledgeContent,
    detail,
    setDetail,
    data,
    type,
    setType,
    getKnowledgeIndex,
    editKnowledgeContent,
    dataList,
    setDataList,

    getLligentAgent,
    ligentAgentData,
    setLigentAgentData,
    angentVisible,
    setAngentVisible,
    formAgent,
    applyVisible,
    setApplyVisible,

    formApply,
    activeKey,
    setActiveKey,
    applyKnowledgeData,
    disabled,
    setDisabled,
    actionRef,
    addUserVisible,
    setAddUserVisible,
    getUser,
    addUserList,
    permisionVisible,
    setPermisionVisible,
    updateDept,
    deleteDept,
    userData,
    setUserData,
    total,
  };
});
